package com.tansun.easycare.rule.policytree.gzip;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 对策略树页面进行压缩
 */
public class GzipFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(GzipFilter.class);

    public void destroy() {
    }

    /**
     * 判断浏览器是否支持GZIP
     */
    private static boolean isGZipEncoding(HttpServletRequest request) {
        boolean flag = false;
        String encoding = request.getHeader("Accept-Encoding");
        if (encoding.indexOf("gzip") != -1) {
            flag = true;
        }
        return flag;
    }

    /**
     * 过滤方法
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            if (isGZipEncoding(req)) {
                GzipWrapper wrapper = new GzipWrapper(resp);
                chain.doFilter(request, wrapper);
                byte[] gzipData = gzip(wrapper.getResponseData());
                resp.addHeader("Content-Encoding", "gzip");
                resp.setContentLength(gzipData.length);
                ServletOutputStream output = response.getOutputStream();
                output.write(gzipData);
                output.flush();
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

    }

    /**
     * 初始化方法
     */
    public void init(FilterConfig arg0) throws ServletException {

    }

    private byte[] gzip(byte[] data) {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240);
        GZIPOutputStream output = null;
        try {
            output = new GZIPOutputStream(byteOutput);
            output.write(data);
        } catch (IOException e) {
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
            }
        }
        return byteOutput.toByteArray();
    }

}